<template>
  <el-container>
    <router-link to="/process/formRead"></router-link>
    <el-main>
      <div class="textmain">
        <!-- 表单模块 -->
        <div class="left-content">
            <div class="left-from"  style="overflow:auto">
              <el-form class="form-text" :rules="rules" ref="form" :model="form"  label-width="80px">
                <el-form-item label="文件标题" prop="subject">
                  <el-input v-model="form.subject" clearable></el-input>
                </el-form-item>
                <el-row>
                  <el-col class="line" :span="12">
                    <el-form-item label="拟稿部门" prop="writerdept">
                      <el-input v-model="form.writerdept" clearable readonly></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col class="line" :span="12">
                    <el-form-item label="拟稿人" prop="writercn">
                      <el-input v-model="form.writercn"  clearable readonly></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col class="line" :span="12">
                    <el-form-item label="拟稿时间" prop="writedate">
                      <el-input v-model="form.writedate" readonly></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col class="line" :span="12" >
                    <el-form-item label="公文类型" prop="redtitle">
                      <el-select v-model="form.filewordId" placeholder="请选择字号"  @change="wordChange" >
                        <el-option v-for="item in filewordlist"
                               :key="item.id"
                              :label="item.fileType"
                              :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col class="line" :span="16">
                    <el-form-item label="文件编号" prop="fileno">
                      <el-input v-model="form.fileno" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col class="line" :span="12">
                    <el-form-item label="密级" prop="secretlevel">
                      <el-select v-model="form.secretlevel" placeholder="请选择密级">
                        <el-option label="一般" value="1"></el-option>
                        <el-option label="商密级" value="2"></el-option>
                        <el-option label="商机级" value="3"></el-option>
                        <el-option label="商绝级" value="4"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col class="line" :span="12">
                    <el-form-item label="缓急" prop="urgencylevel">
                      <el-select v-model="form.urgencylevel" placeholder="请选择缓急">
                        <el-option label="一般" value="1"></el-option>
                        <el-option label="急" value="2"></el-option>
                        <el-option label="特级" value="3"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col class="line" :span="20">
                    <el-form-item label="主送" >
                      <el-input v-model="form.mainsend" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col class="line" :span="20">
                    <el-form-item label="抄报" >
                      <el-input v-model="form.copyreport" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col class="line" :span="20">
                    <el-form-item label="抄送" >
                      <el-input v-model="form.copysend" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="left-button">
              <el-button  type="success" icon="el-icon-check" @click="onSubmit">提交</el-button>
              <el-button type="primary" icon="el-icon-star-off" @click="onSave">保存</el-button>
              <el-button type="danger" icon="el-icon-delete">取消</el-button>
            </div>
        </div>
        <div class="right-content">
            <div class="right-textArea">
              <div id="wangEditorText"></div>
            </div>
            <div class="right-files" style="overflow:auto">
              <el-upload
                class="fwgl_upload"
                ref="upload"
                :headers="upload.headers"
                :disabled="upload.isUploading"
                :action="upload.url+ '?docunid=' + this.form.docunid"
                :before-upload="handleBeforeUpload"
                :on-preview="handlePreview"
                :on-change="handleChange"
                :on-success="handSuccess"
                :on-remove="handleRemove"
                :file-list="fileList"
                :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传{{this.upload.fileType.toString()}}文件，且不超过{{this.upload.fileSize}}MB</div>
              </el-upload>
             <!-- <file-upload
              :fileSize="5"
              :fileType="this.upload.fileType"
              :uploadFileUrl="upload.url+ '?docunid=' + this.form.docunid"
              /> -->
            </div>
        </div>
      </div>
    </el-main>
    <processForm v-if="processFormFlag" :taskId="taskId" ref="processForm" @getProcessSubmitData="getProcessSubmitData" :processFormData="processFormData"></processForm>
  </el-container>
</template>

<script>
  // 引入 wangEditor
  import wangEditor from 'wangeditor'
  import {formatDate} from '@/utils/index.js'
  import { getToken } from "@/utils/auth"
  import { listFileWord } from "@/api/system/oa/FileWordConfig"
  import {initProcessFormData} from "@/api/process/processForm.js";
  import processForm from '@/components/oa/processForm/index.vue'
  //import fileUpload from '@/components/FileUpload'
  import {listFwgl, getFwgl, delFwgl, addFwgl, updateFwgl, exportFwgl,uploadFwglFiles,removeFwglFile,getFwglFiles} from '@/api/fwgl/form.js'
  export default {
    data() {
      return {
		  processFormFlag:false,
        filewordlist:[],
        form: {
          pageNum: 1,
          pageSize: 10,
          papertitle: null,
          writerdept: this.$store.getters.dept.deptName,
          writercn: this.$store.getters.name,
          writerid: this.$store.getters.id,
          writedate: formatDate(new Date()),
          fileword: null,
          fileyear: null,
          fileno: null,
          secretlevel: null,
          urgencylevel: null,
          subject: null,
          mainsend: null,
          copyreport: null,
          copysend: null,
          redtitle: null,
          wordcontent: null,
          wordcontenthtml: null,
          rightdept: null,
          leftdept: null,
          printtime: null,
          readers: 'admin',
          author: 'admin',
          signerpublish: null,
          filewordId:null,
          docunid:null,
          processDefinitionKey:'',
        },
        submitData:null,
        rules: {
          subject: [
            { required: true, message: '请输入文件标题', trigger: 'blur' }
          ],
          writercn: [
            { required: true, message: "请输入拟稿人名称", trigger: "blur" }
          ],
          writerdept: [
            { required: true, message: "请输入拟稿部门", trigger: "blur" }
          ],
          writedate: [
            {
              required: true, message: '起草时间不能为空', trigger: 'blur'
            }
          ],
          fileno: [
            {
              required: true, message: '文件编号不能为空', trigger: 'blur'
            }
          ],
          secretlevel: [
            { required: true, message: "密级不能为空", trigger: "blur" }
          ],
          urgencylevel: [
            { required: true, message: "缓急不能为空", trigger: "blur" }
          ],
          redtitle:[
            { required: true, message: "发文类型不能为空", trigger: "blur" }
          ]
        },
        fileList: [],
        // 附件上传
        upload: {
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/fwgl/form/upload",
          // 文件类型, 例如['png', 'jpg', 'jpeg']
          fileType:["doc", "xls", "ppt", "txt", "pdf"],
          //文件大小
          fileSize:5,

        },
        processFormData:'',/* {
          routerData:[
            {
              id:0,
              routerName:"送室经理审核",
              userTasks:[
                {
                  userTaskName:"室审核",
                  userTaskId:"T001",
                  userChoiceType:"null",
                  singleUser:true,
                },
                {
                  userTaskName:"中心审核",
                  userTaskId:"T002",
                  userChoiceType:"103",
                  singleUser:true,
                },
              ],
            },
            {
              id:1,
              routerName:"送部门审核",
              userTasks:[
                {
                  userTaskName:"部门审核",
                  userTaskId:"T003",
                  userChoiceType:"null",
                  singleUser:true,
                },
              ],
            },
          ],
          remarkOptions:[
            {
              value:"0",
              label:"同意",
            },
            {
              value:"1",
              label:"不同意",
            },
          ]
        }, */
        editor: null,
        PDFdom : '',
      }
    },
    components: {
      processForm
    },
    computed:{
    },
    created() {
      if(this.pDocUnid != ''){
        this.docunid = this.pDocUnid
        this.initsaveForm(this.pDocUnid)
      }
      if(this.processKey){
        this.form.processDefinitionKey = this.processKey
      }
    },
    props: {
      pDocUnid:{
        type:String,
        default:null
      },
      processKey:{
        type:String,
        default:""
      },
	taskId:{
		type:String,
		default:null
	}
    },
    methods: {
      //提交表单
      onSubmit() {
        //uploadFwglFiles(this.form);
        this.$refs["form"].validate(valid => {
          if(this.editor.txt.text().trim()=="" || this.editor.txt.text().trim()==null ){
           this.$message({
              showClose: false,
              message: '正文不准为空，请编辑正文',
              type: "error",
              duration:2000
            })
            return false
          }
          this.form.wordcontent = this.editor.txt.text()
          if (valid) {
            initProcessFormData(this.form.processDefinitionKey, this.taskId).then(response => {
              this.processFormData = response.data;
              this.processFormFlag=true;
              this.$nextTick(()=>{
                this.$refs.processForm.showProcessFormDialog(true);
              })

            });

            console.log("后端请求来的数据：", this.processFormData);
            /* this.$confirm("是否提交？",'提示',{
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {

            }) */
          }
        });
      },
      //删除附件
      handleRemove(file, fileList) {
        removeFwglFile(file.id);
        console.log(file.id);
      },
      handlePreview(file) {
        console.log(file);
      },
      //每次上传新的文件就提交一次
      handleChange(file, fileList) {
        //this.fileList = fileList.slice(-3);
        this.$refs.upload.submit();
      },
      //上传成功
      handSuccess(response, file, fileList){
        file.id = response
      },
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        // 校检文件类型
        if (this.upload.fileType) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          const isTypeOk = this.upload.fileType.some((type) => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
          if (!isTypeOk) {
            this.$message.error(`文件格式不正确, 请上传${this.upload.fileType.join("/")}格式文件!`);
            return false;
          }
        }
        // 校检文件大小
        if (this.upload.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.upload.fileSize;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        return true;
      },
      //给红头信息赋值
      wordChange(){
        console.log(this.filewordlist)
        let filewordObj = this.filewordlist.filter(f => f.id == this.form.filewordId)[0]
        this.form.fileword = filewordObj.wordName
        this.form.rightdept = filewordObj.rightBottom
        this.form.leftdept = filewordObj.leftBottom
        this.form.redtitle = filewordObj.redHead
        console.log( filewordObj)
      },
      uuidGenerator() {
      	var originStr = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      		originChar = '0123456789ABCDEF',
      		len = originChar.length;
      	return originStr.replace(/x/g, function(match) {
      		return originChar.charAt(Math.floor(Math.random() * len))
      	})
      },
      //保存
      onSave(){
        this.$refs["form"].validate(valid => {
          if(this.editor.txt.text().trim()=="" || this.editor.txt.text().trim()==null ){
           this.$message({
              showClose: false,
              message: '正文不准为空，请编辑正文',
              type: "error",
              duration:2000
            })
            return false
          }
          this.form.wordcontent = this.editor.txt.text()
          if (valid) {
            this.$confirm("是否保存？",'提示',{
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              updateFwgl(this.form).then(response => {
                this.msgSuccess("保存成功");
              })
            })
          }
        });
        //this.$emit('clickisEdit',false);
      },
      //获取处理单数据
      getProcessSubmitData(submitData){
        console.log("submitData",submitData)
        this.submitData = submitData
        addFwgl(this.form,this.submitData).then(response => {
          this.msgSuccess("提交成功")
          this.$refs.processForm.showProcessFormDialog(false);
          /* this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.go(-1) */
          //关闭当前标签
          this.closeSelectedTag(this.$route)
          // /this.getList();
        });
      },
      //初始化已保存表单数据
      initsaveForm(donUnid){
        getFwgl(donUnid).then((response) => {
          this.form =  response.data;
          //初始化editor内容
          this.editor.txt.html(response.data.wordcontenthtml)
        }).then(() => {
          console.log(this.form)
        }).catch((err) => {
          console.log(err)
        })
        getFwglFiles(donUnid).then(response => {
          console.log("file:===")
          console.log(response)

          for(let file of response.rows ){
            this.fileList.push({
              name:file.filename,
              url:file.filepath
            })
            console.log(file)
          }

        }).catch((err) => {
          console.log(err)
        })
      },
      //关闭当前标签
      closeSelectedTag(view) {
        this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
          this.toLastView(visitedViews, view)
        })
      },
      //退回上一个标签
      toLastView(visitedViews, view) {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView.fullPath)
        } else {
          // now the default is to redirect to the home page if there is no tags-view,
          // you can adjust it according to your needs.
          if (view.name === 'Dashboard') {
            // to reload home page
            this.$router.replace({ path: '/redirect' + view.fullPath })
          } else {
            this.$router.push('/')
          }
        }
      }
    },
    mounted () {
       //初始化docunid
       if(this.form.docunid != null){
         this.form.docunid = this.uuidGenerator()
       }
      // eslint-disable-next-line new-cap
      const editor = new wangEditor('#wangEditorText')

      // 配置 onchange 回调函数，将数据同步到 vue 中
      editor.config.onchange = (newHtml) => {
        this.form.wordcontenthtml = newHtml
      }
      editor.config.customUploadImg = function (resultFiles, insertImgFn) {
          // resultFiles 是 input 中选中的文件列表
          // insertImgFn 是获取图片 url 后，插入到编辑器的方法

          // 上传图片，返回结果，将图片插入到编辑器中
          console.log(resultFiles)
          let reader = new FileReader()
          reader.readAsDataURL(resultFiles[0])
          reader.onload = () => {
             insertImgFn(reader.result)
          }
          reader.onerror = function (error) {
            console.log('Error: ', error)
          }

      }
      editor.config.showLinkImg = false
      //设置高度
      let formHeight =  document.querySelector('.left-from').offsetHeight-82
      console.log(formHeight)
      editor.config.height =formHeight
      // 创建编辑器
      editor.create()

      this.editor = editor

      //获取文号
      let now = new Date();
      //初始化年号
      this.form.fileyear = now.getFullYear();
      //获取文号list
      listFileWord().then(response => {
         this.filewordlist = response.rows;
      });
      //this.FileWordList = listFileWord().rows;
    },
    beforeDestroy () {
      // 调用销毁 API 对当前编辑器实例进行销毁
      this.editor.destroy()
      this.editor = null
    },
    beforeCreate() {
      //console.log(this.$route.query)
    }
  }
</script>

<style>
  .textmain{

  }
  .left-content{
    width: 48%;
    height: 700px;
    float: left;
    box-shadow: 0 2px 14px rgba(0, 0, 0, .12), 0 0 16px rgba(0, 0, 0, .04);
    padding: 10px;
  }
  .left-from{
    height: 80%;
    border-radius: 4px;
    border: 1px solid #f1f1f1;
  }
  .left-button{
    margin-top: 10px;
    height: 15%;
    border-radius: 4px;
    /* border: 1px solid #f1f1f1; */
    padding-top: 5%;
    text-align: center;
  }
  .right-content{
    width: 48%;
    height: 700px;
    float: right;
    box-shadow: 0 2px 14px rgba(0, 0, 0, .12), 0 0 16px rgba(0, 0, 0, .04);
    padding: 10px;
  }
  .right-textArea{
    height: 80%;
  }
  .right-files{
    margin-top: 10px;
    height: 15%;
    border-radius: 4px;
    border: 1px solid #f1f1f1;
    padding: 5px;
  }
  .form-text{
    padding: 5px;
  }
  .w-e-toolbar {
      display: flex;
      padding: 0 6px;
      flex-wrap: wrap;
      position: relative!important;
      z-index: 101!important;
  }
  .w-e-text-container {
      position: relative!important;
      height: 100%;
      z-index: 100!important;
  }

</style>
